﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.DepConsul
{
    public static class ConsulExtend
    {
        public static IApplicationBuilder UseConsul(this IApplicationBuilder app, IConfiguration configuration)
        {
            ConsulRegistOption consulRegisterOption = new();
            configuration.Bind("ConsulRegist", consulRegisterOption);
            ConsulClientOption consulClientOption = new();
            configuration.Bind("ConsulClient", consulClientOption);

            if (consulRegisterOption.HealthCheck.Contains("{0}:{1}"))
            {
                consulRegisterOption.HealthCheck = string.Format(consulRegisterOption.HealthCheck, consulRegisterOption.Address, consulRegisterOption.Port);
            }

            using (var consulClient = new ConsulClient(x =>
            {
                x.Address = new Uri(consulClientOption.Address);
                x.Datacenter = consulClientOption.Datacenter;
            }))
            {
                var registration = new AgentServiceRegistration()
                {
                    ID = Guid.NewGuid().ToString(),
                    Name = consulRegisterOption.Name,// 服务名
                    Address = consulRegisterOption.Address, // 服务绑定IP(也就是你这个项目运行的ip地址)
                    Port = consulRegisterOption.Port, // 服务绑定端口(也就是你这个项目运行的端口)
                    Tags = new string[] { consulRegisterOption.Weight.ToString() },//标签
                    Check = new AgentServiceCheck()
                    {
                        Interval = TimeSpan.FromSeconds(12),//健康检查时间间隔
                        HTTP = consulRegisterOption.HealthCheck,//健康检查地址
                        Timeout = TimeSpan.FromSeconds(5),
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(20)//失败后多久移除
                    }
                };
                // 服务注册
                consulClient.Agent.ServiceRegister(registration).Wait();
            }
            Console.WriteLine($"{JsonConvert.SerializeObject(consulRegisterOption)} 完成注册");
            return app;
        }
    }
}
